package com.heima.user.service.impl;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.message.FollowBehaviorConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 *
 */
@Service
@Slf4j
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    ArticleFeign articleFeign;

    @Resource
    ApUserMapper apUserMapper;

    @Autowired
    ApUserFollowMapper apUserFollowMapper;
    @Autowired
    ApUserFanMapper apUserFanMapper;
    // 关注与取消关注
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        // 检查参数
        if (dto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 根据作者id查询作者信息
        ApAuthor apAuthor = articleFeign.selectById(dto.getAuthorId());
        if (apAuthor == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"作者信息不存在");
        }
        // 判断当前是否有用户登陆
        ApUser loginUser = AppThreadLocalUtils.getUser();
        if (loginUser == null){
            throw new CustomException(AppHttpCodeEnum.USER_NOT_EXIST,"未登录无法进行关注操作");
        }
        if (apAuthor.getId() == loginUser.getId()){
            throw new CustomException(AppHttpCodeEnum.ILLEGAL_USER,"自已不能关注自己");
        }
        // 根据操作方式判断是关注还是取关
        if (dto.getOperation() == 0){
            return followByUserId(apAuthor,loginUser.getId(),dto.getArticleId());
        }else {
            return followCancelByUserId(apAuthor,loginUser.getId());
        }
    }

    private ResponseResult followCancelByUserId(ApAuthor apAuthor, Integer loginId) {

        apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, apAuthor.getId())
                .eq(ApUserFollow::getUserId, loginId));

        apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId,loginId)
                .eq(ApUserFan::getUserId,apAuthor.getId()));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    @Autowired
    KafkaTemplate kafkaTemplate;

    private ResponseResult followByUserId(ApAuthor apAuthor, Integer loginId,Long articleId) {

        // 查看是否已经被关注过
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, apAuthor.getUserId())
                .eq(ApUserFollow::getUserId, loginId));
        if (apUserFollow != null){
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"已经关注过该作者,不可重复关注");
        }

        // 根据当前用户id查询当前用户信息
        ApUser apUser = apUserMapper.selectById(loginId);

        // 关注需要新建关注表信息
        // 对其进行赋值
        apUserFollow = new ApUserFollow();
        apUserFollow.setUserId(loginId);
        apUserFollow.setFollowId(apAuthor.getUserId());
        apUserFollow.setFollowName(apAuthor.getName());
        apUserFollow.setLevel((short)0);
        apUserFollow.setIsNotice(false);
        apUserFollow.setCreatedTime(new Date());
        apUserFollowMapper.insert(apUserFollow);


        // 新建粉丝表
        ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getFansId,loginId)
                .eq(ApUserFan::getUserId,apAuthor.getUserId()));
        if (apUserFan != null){
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"已经关注过该作者,不可重复关注");
        }

        apUserFan = new ApUserFan();
        apUserFan.setUserId(apAuthor.getUserId());
        apUserFan.setFansId(Long.valueOf(loginId));
        apUserFan.setFansName(apUser.getName());
        apUserFan.setLevel((short)0);
        apUserFan.setCreatedTime(new Date());
        apUserFan.setIsDisplay(false);
        apUserFan.setIsShieldLetter(false);
        apUserFan.setIsShieldComment(false);
        apUserFanMapper.insert(apUserFan);

        FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
        followBehaviorDto.setArticleId(articleId);
        followBehaviorDto.setFollowId(apAuthor.getId());
        followBehaviorDto.setUserId(loginId);
        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(followBehaviorDto));


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);


    }
}
